package com.yuanda.wordhot.web.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.yuanda.wordhot.entity.UserEntity;
import com.yuanda.wordhot.service.UserService;
import com.yuanda.wordhot.util.ContextUtil;

/**
 * 
 */
@Component
public class CurrentUserInterceptor extends HandlerInterceptorAdapter {

	@Autowired
	private UserService userService;
	
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		ContextUtil.setRequest(request);
		ContextUtil.setResponse(response);
		return super.preHandle(request, response, handler);
	}

	@Override
	public void postHandle(HttpServletRequest httpServletRequest,
			HttpServletResponse httpServletResponse, Object o,
			ModelAndView modelAndView) throws Exception {
		UserEntity currentUser = ContextUtil.getCurrentUser();
		if (currentUser == null && (currentUser=userService.getCurrentUser())!=null) {
			ContextUtil.setCurrentUser(currentUser);
		}
	}
}
